﻿ using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraPrinting;

namespace TDesktop.Communication
{
    internal partial class MainControl : XtraUserControl
    {
        private DataTable childTable = null;
        private DataTable projectTable = null;

        private int nowRow = -1;

        public MainControl()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, System.EventArgs e)
        {
            DP_StartTime.DateTime = DP_OverTime.DateTime = DateTime.Now;
            gridControl1.DataSource = null;
            InitProject();
        }

        #region 项目CombBox

        /// <summary>
        /// 初始化项目目录
        /// </summary>
        private void InitProject()
        {
            cb_project.Properties.Items.Clear();
            projectTable = Unity.GetProjectFromXml(Unity.ProjectPath);
            for (int i = 0; i < projectTable.Rows.Count; i++)
            {
                cb_project.Properties.Items.Add(projectTable.Rows[i][0]);
            }
        }
        /// <summary>
        /// 更改事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cb_project_SelectedIndexChanged(object sender, EventArgs e)
        {
            string projectName = cb_project.Text;
            string path = string.Format(Unity.ChildProjectPath, projectName);//设置路径

            childTable = Unity.GetChildProjectFromXml(path);

            //如果绑定过数据，则先保存之前的数据
            if (gridControl1.DataSource != null)
            {
                DataTable tempTable = gridControl1.DataSource as DataTable;
                tempTable.WriteXml(string.Format(Unity.ChildProjectPath, tempTable.TableName), XmlWriteMode.WriteSchema);
            }

            gridControl1.DataSource = childTable;

            Unity.SetColumnEdit(gridView1);
            ClearInfo();

            gridView1.BestFitColumns();
        }

        #endregion

        #region 窗口相关事件

        /// <summary>
        /// 新增按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNew_Click(object sender, EventArgs e)
        {
            if (gridControl1.DataSource == null)
            {
                XtraMessageBox.Show(this, "请先选择项目", "提示");
                return;
            }

            //gridView1.AddNewRow();
            childTable.Rows.Add(new DataRow[] { });

            #region 转到最后一行

            int index = gridView1.DataRowCount - 1;
            this.gridView1.FocusedRowHandle = index;
            ClearInfo();
            nowRow = index;
            ReadRowData(index);

            #endregion

        }

        /// <summary>
        /// 删除按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDel_Click(object sender, EventArgs e)
        {
            if (gridControl1.DataSource == null)
            {
                XtraMessageBox.Show(this, "请先选择项目", "提示");
                return;
            }
            if (XtraMessageBox.Show(this, "确定删除？", "问题", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            gridView1.DeleteRow(gridView1.FocusedRowHandle);
            childTable.WriteXml(string.Format(Unity.ChildProjectPath, cb_project.Text), XmlWriteMode.WriteSchema);
        }

        /// <summary>
        /// 鼠标点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridControl1_MouseClick(object sender, MouseEventArgs e)
        {
            //GridHitInfo info = gridView1.CalcHitInfo(this.PointToClient(MousePosition));
            ////如果点在行里
            //if (info.InRow)
            //{
            //    int index = info.RowHandle;
            //    if (index == nowRow)
            //    {
            //        return;
            //    }
            //    ClearInfo();
            //    nowRow = index;
            //    ReadRowData(index);
            //}
        }

        /// <summary>
        /// 选中行变更
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            int index = e.FocusedRowHandle;
            if (index < 0) return;
            if (index == nowRow)
            {
                return;
            }
            ClearInfo();
            nowRow = index;
            ReadRowData(index);
            //刷新列表
            gridView1.BestFitColumns();
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInfo_Save_Click(object sender, EventArgs e)
        {
            if (gridControl1.DataSource == null)
            {
                XtraMessageBox.Show(this, "请先选择项目", "提示");
                return;
            }
            WriteRowData(gridView1.GetSelectedRows()[0]);
        }

        /// <summary>
        /// 窗口关闭保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        /// <summary>
        /// 项目按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProject_Click(object sender, EventArgs e)
        {
            ProjectInfo.GetFrm(projectTable, MousePosition).ShowDialog(this);

            Form1_Load(null, null);
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnToExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Title = "导出Excel";
            fileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
            fileDialog.FileName = cb_project.Text + "_用户沟通记录.xlsx";
            DialogResult dialogResult = fileDialog.ShowDialog(this);
            if (dialogResult == DialogResult.OK)
            {
                DevExpress.XtraPrinting.XlsxExportOptionsEx options = new DevExpress.XtraPrinting.XlsxExportOptionsEx();
                options.ShowGridLines = false;
                options.TextExportMode = TextExportMode.Text;


                gridControl1.ExportToXlsx(fileDialog.FileName, options);
                DevExpress.XtraEditors.XtraMessageBox.Show("保存成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                System.Diagnostics.Process.Start("Explorer.exe", Path.GetDirectoryName(fileDialog.FileName));
            }
        }

        #endregion

        #region 读写

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="index"></param>
        private void ReadRowData(int index)
        {
            #region 获取数据

            List<string> dataList = Unity.GetAllData(index, gridView1);

            #endregion

            #region 设置数据

            #region 日期

            //日期
            try
            {
                DP_StartTime.DateTime = DateTime.Parse(dataList[0].ToString());
            }
            catch (Exception)
            {
                DP_StartTime.DateTime = DateTime.Today;
            }

            #endregion

            #region 问题来源

            //问题来源
            cb_QusetionFrom.Properties.Items.Clear();
            List<string> list = Unity.GetAllQuestionFrom(gridView1);
            int cbq_index = 0;
            for (int i = 0; i < list.Count; i++)
            {
                cb_QusetionFrom.Properties.Items.Add(list[i]);
                if (dataList[1].ToString() == list[i])
                    cbq_index = i;  //查找是
            }
            cb_QusetionFrom.SelectedIndex = cbq_index;

            #endregion

            #region 问题简述

            textBox_Info.Text = dataList[2].ToString();

            #endregion

            #region 是否解决

            if (dataList[3].ToString() == "已解决")
            {
                rBtnYes.Checked = true;
            }
            if (dataList[3].ToString() == "未解决")
            {
                rBtnNo.Checked = true;
            }

            #endregion

            #region 解决方案

            TextBox_Jiejue.Text = dataList[4].ToString();

            #endregion

            #region 解决时间

            try
            {
                DP_OverTime.DateTime = DateTime.Parse(dataList[5].ToString());
            }
            catch (Exception)
            {
                DP_OverTime.DateTime = DateTime.Today;
            }

            #endregion

            #endregion
        }

        /// <summary>
        /// 写入数据
        /// </summary>
        /// <param name="index"></param>
        private void WriteRowData(int index)
        {
            #region 准备数据

            List<string> dataList = new List<string>();

            #region 日期

            //日期
            dataList.Add(DP_StartTime.Text);

            #endregion

            #region 问题来源

            //问题来源
            dataList.Add(cb_QusetionFrom.Text);

            #endregion

            #region 问题简述

            dataList.Add(textBox_Info.Text);

            #endregion

            #region 是否解决

            if (rBtnYes.Checked == true)
            {
                dataList.Add("已解决");
            }
            else if (rBtnNo.Checked == true)
            {
                dataList.Add("未解决");
            }
            else
            {
                dataList.Add("");
            }

            #endregion

            #region 解决方案

            dataList.Add(TextBox_Jiejue.Text);

            #endregion

            #region 解决时间

            if (dataList[3] != "")
            {
                dataList.Add(DP_OverTime.Text);
            }
            else
            {
                dataList.Add("");
            }

            #endregion

            #endregion

            Unity.SetAllData(index, dataList, gridView1);
            childTable.WriteXml(String.Format(Unity.ChildProjectPath, cb_project.Text), XmlWriteMode.WriteSchema);
        }
        #endregion

        #region 相关
        private void ClearInfo()
        {
            DP_StartTime.DateTime = DP_OverTime.DateTime = DateTime.Now;
            cb_QusetionFrom.Properties.Items.Clear();
            cb_QusetionFrom.Text = null;
            TextBox_Jiejue.Text = textBox_Info.Text = null;
            rBtnNo.Checked = rBtnYes.Checked = false;
            xtraTabControl1.SelectedTabPageIndex = 0;
            nowRow = -1;
        }

        #endregion

        /// <summary>
        /// 行背景色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            int index = e.RowHandle;
            if (index < 0) return;
            DataRow dr = this.gridView1.GetDataRow(index);
            if (dr == null) return;
            e.Appearance.ForeColor = Color.Black;

            if (dr[3].ToString() == "")
            {
                e.Appearance.BackColor = Color.FromArgb(252, 247, 198);
            }
            if (dr[3].ToString() == "已解决")
            {
                e.Appearance.BackColor = Color.FromArgb(188, 254, 205);
            }

            if (dr[3].ToString() == "未解决")
            {
                e.Appearance.BackColor = Color.FromArgb(254, 191, 191);
            }
        }

    }
}
